package com.shopping_back.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.common.Result;
import com.shopping_back.pojo.dto.ProductDTO;
import com.shopping_back.pojo.dto.PromotionConfigDTO;
import com.shopping_back.pojo.entity.*;
import com.shopping_back.pojo.vo.MerchantInfoVO;
import com.shopping_back.pojo.vo.OrderVO;
import com.shopping_back.pojo.vo.ProductVO;
import com.shopping_back.pojo.vo.ShipOrderVO;
import com.shopping_back.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商家信息表 前端控制器
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@RestController
@RequestMapping("/api/merchant-info")
@RequiredArgsConstructor
public class MerchantInfoController {

    private final IMerchantInfoService merchantInfoService;

    private final IUserAccountService userAccountService;

    private final IOrderMainService orderMainService;

    private final ISpuService spuService;

    private final IPromotionActivityService promotionActivityService;

    /**
     * 商户资质审核（入驻审批）
     * 前端传入 JSON：
     * {
     *   "userId": 123,
     *   "auditStatus": 1,         // 1=通过;2=拒绝
     *   "rejectReason": "xxx"     // 拒绝时填写
     * }
     */
    @PutMapping("/audit")
    public Result audit(@RequestBody MerchantInfo merchantInfo) {
        // 如果审核通过清空 rejectReason 字段
        if (merchantInfo.getAuditStatus() != null && merchantInfo.getAuditStatus() == 1) {
            merchantInfo.setRejectReason(null);
        }

        // 只更新 auditStatus 和 rejectReason 两个字段
        merchantInfoService.updateById(merchantInfo);
        return Result.success();
    }

    @PostMapping("/save")
    public Result saveMerchantInfo(@RequestBody MerchantInfoVO merchantInfo) {
        try {
            // 调用服务层保存商户信息
            Object savedInfo = merchantInfoService.saveMerchantInfo(merchantInfo);
            return Result.success(savedInfo, "商户信息保存成功");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error("500", "系统繁忙，请稍后重试");
        }
    }

    /**
     * 获取所有待审核商户列表（auditStatus = 0）
     */
    @GetMapping("/pending")
    public Result getPending() {
        List<MerchantInfo> list = merchantInfoService.list(
                new LambdaQueryWrapper<MerchantInfo>()
                        .eq(MerchantInfo::getAuditStatus, 0)
        );
        return Result.success(list);
    }

    @GetMapping("/{userId}")
    public Result getById(@PathVariable Long userId) {
        MerchantInfo info = merchantInfoService.getById(userId);
        return Result.success(info);
    }

    @PostMapping("/update")
    public Result updateMerchantInfo(@RequestParam Long userId, @RequestParam String shopName) {
        merchantInfoService.updateMerchantInfo(userId, shopName);
        return Result.success();
    }

    @PostMapping("/reset-password")
    public Result resetPassword(@RequestParam Long userId, @RequestParam String password, @RequestParam String rePassword) {
        userAccountService.resetPassword(userId, password, rePassword);
        return Result.success();
    }

    @GetMapping("/orders")
    public Result getMerchantOrders(
            @RequestParam Long merchantId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<OrderVO> orders = orderMainService.getMerchantOrders(merchantId, page, size);
        return Result.success(orders);
    }

    @PostMapping("/ship-order")
    public Result shipOrder(@RequestBody ShipOrderVO request) {
        orderMainService.shipOrder(request);
        return Result.success();
    }

    //获取商户名下的商品
    @GetMapping("/products")
    public Result getProducts(
            @RequestParam Long merchantId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<ProductVO> products = spuService.getProducts(merchantId, page, size);
        return Result.success(products);
    }

    @PostMapping("/product")
    public Result createProduct(@RequestBody ProductDTO productDTO) {
        spuService.createProduct(productDTO);
        return Result.success();
    }

    @PutMapping("/product")
    public Result updateProduct(@RequestBody ProductDTO productDTO) {
        spuService.updateProduct(productDTO);
        return Result.success();
    }

    @PutMapping("/product/changeStatus")
    public Result toggleProductStatus(@RequestParam Long spuId, @RequestParam Integer status) {
        spuService.toggleProductStatus(spuId, status);
        return Result.success();
    }

    @GetMapping("/promotions")
    public Result getPromotions(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "10") int size) {
        return Result.success(promotionActivityService.page(new Page<>(page, size)));
    }

    // 获取SKU列表
    @GetMapping("/skus")
    public Result getSkus(@RequestParam Long id) {
        return Result.success(promotionActivityService.getSkus(id));
    }

    @GetMapping("/skusByAd")
    public Result getSkus() {
        return Result.success(promotionActivityService.getSkusByAd());
    }

    @PostMapping("/seckill-items")
    public Result addSeckillItem(@RequestBody SeckillItem seckillItem) {
        promotionActivityService.addSeckillItem(seckillItem);
        return Result.success();
    }

    @PostMapping("/groupbuy-item")
    public Result addGroupbuyItem(@RequestBody GroupbuyItem item) {
        promotionActivityService.addGroupbuyItem(item);
        return Result.success();
    }

    @PostMapping("/full-reduction-item")
    public Result addFullReductionItem(@RequestBody FullReductionItem item) {
        promotionActivityService.addFullReductionItem(item);
        return Result.success();
    }

    @PostMapping("/combo-item")
    public Result addComboItem(@RequestParam Long activityId, @RequestParam Long skuId) {
        promotionActivityService.addComboItem(activityId, skuId);
        return Result.success();
    }

    @GetMapping("/promotion-items")
    public Result getPromotionItems(@RequestParam Long activityId, @RequestParam Integer type) {
        return Result.success(promotionActivityService.getPromotionItems(activityId, type));
    }

    @DeleteMapping("/promotion-item")
    public Result deletePromotionItem(@RequestParam Long activityId, @RequestParam Long skuId, @RequestParam Integer type) {
        promotionActivityService.deletePromotionItem(activityId, skuId, type);
        return Result.success();
    }

    @PutMapping("/promotion/config")
    public void updatePromotionConfig(@RequestBody PromotionConfigDTO config) {
        promotionActivityService.updatePromotionConfig(config);
    }


}
